from utils.tencent.cos import delete_bucket
from web import models
from django.shortcuts import render, redirect
from web.form.settings import PasswordChangeForm

def setting(request, project_id):
    return render(request, 'settings.html')


def setting_delete(request, project_id):
    """ 删除项目 """
    if request.method == "GET":
        return render(request, 'setting_delete.html')
    # 校验项目名称
    project_name = request.POST.get('project_name')
    if not project_name or project_name != request.tracer.project.name:
        return render(request, "setting_delete.html", {"error": "项目名称不匹配"})

    # 项目名写对了则删除（只有创建者可以删除）
    if request.tracer.user != request.tracer.project.creator:
        return render(request, 'setting_delete.html', {'error': '只有创建者可以删除项目'})

    # 1.删除桶
    #   -删除桶中所有文件（找到桶中的所有文件 + 删除文件）
    #   -删除桶中所有碎片（找到桶中所有碎片 + 删除碎片）
    #   -删除桶（删除桶）
    # 2.删除项目
    #   -项目删除

    delete_bucket(request.tracer.project.bucket, request.tracer.project.region)
    models.Project.objects.filter(id=request.tracer.project.id).delete()


    return redirect('project_list')

def setting_password(request, project_id):
    """ 修改密码 """
    if request.method == "GET":
        form = PasswordChangeForm(user=request.tracer.user)
        return render(request, 'setting_password.html', {'form': form})

    if request.method == "POST":
        form = PasswordChangeForm(user=request.tracer.user, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')  # 修改为用户个人信息页面
        else:
            return render(request, 'setting_password.html', {'form': form})
    #return redirect('index')